Mongoose Model

Once we have a schema, we should generate a model!

import mongoose from "mongoose";
import NoteSchema from "./NoteSchema.js"

const Note = mongoose.model("Note", NoteSchema);

export default Note;

A model must be linked to a document schema. Notice the first argument to mongoose.model is the singular name for the entity your model is for. This is because Mongoose automatically looks for the plural, lowercased version of your model name as the collection that holds documents of that model. Therefore, the model "Note" will result in constructing a notes collection in the database.

Now we can use the model to construct documents, as shown in the example below:

import Note from "./Note.js";
import faker from "faker";

Note.create(
  {
    title: faker.lorem.sentence(),
    text: faker.lorem.paragraph(),
  },
  (err, note) => {
    console.log(err ? err : note);
  }
);

The create method allows you to create documents of that model. It takes two arguments: an object representing the data to be saved in the database, and a callback function. It invokes the callback function by passing two arguments to it: an error (which will be null if there was no error) and the document created (which will be null if there was an error).

The Mongoose model is a Data Access Object, exposing operations such as create, find, findById, findByIdAndUpdate, findByIdAndDelete and many more.